package service

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"log"
	"strconv"
)

type Node struct {
	Conn *websocket.Conn
	Data chan []byte
}

var Client map[int32]*Node = make(map[int32]*Node)

type Message struct {
	Form    int32  `json:"form"`
	To      int32  `json:"to"`
	Content string `json:"content"`
}

func Chat(c *gin.Context) {
	form, _ := strconv.Atoi(c.Query("user_id"))

	var upgrader = websocket.Upgrader{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	}

	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		log.Println(err)
		return
	}

	Client[int32(form)] = &Node{
		Conn: conn,
		Data: make(chan []byte),
	}

	go ReadChat(Client[int32(form)])
	go WriteChat(Client[int32(form)])
}

func ReadChat(node *Node) {
	for {
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			return
		}

		var msg Message
		json.Unmarshal(message, &msg)

		messageTo := Client[msg.To].Data
		messageTo <- message
	}
}

func WriteChat(node *Node) {
	for {
		data := <-node.Data
		node.Conn.WriteMessage(websocket.TextMessage, data)
	}
}
